<template>
  <!-- 添加或修改原材料（主材）对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="20">

            <el-col :span="12">
              <el-form-item label="检验编号" prop="inspectNumber">
                <el-input v-model="form.inspectNumber" placeholder="保存后自动生成" disabled/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="原材料制造商" prop="producer">
                <el-input v-model="form.producer" placeholder="请输入原材料制造商"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="牌号" prop="code">
                <el-input v-model="form.code" placeholder="请输入牌号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="炉批号" prop="heatBatchNumber">
                <el-input v-model="form.heatBatchNumber" placeholder="请输入炉批号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来料检验批次号" prop="batchNumber">
                <el-input v-model="form.batchNumber" placeholder="请输入来料检验批次号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-C" prop="cValue">
                <el-input-number v-model="form.cValue" placeholder="请输入化学成分分析-C" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="cValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-P" prop="pValue">
                <el-input-number v-model="form.pValue" placeholder="请输入化学成分分析-P" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="pValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-S" prop="sValue">
                <el-input-number v-model="form.sValue" placeholder="请输入化学成分分析-S" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="sValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Al" prop="alValue">
                <el-input-number v-model="form.alValue" placeholder="请输入化学成分分析-Al" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="alValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Si" prop="siValue">
                <el-input-number v-model="form.siValue" placeholder="请输入化学成分分析-Si" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="siValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Fe" prop="feValue">
                <el-input-number v-model="form.feValue" placeholder="请输入化学成分分析-Fe" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="feValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Cu" prop="cuValue">
                <el-input-number v-model="form.cuValue" placeholder="请输入化学成分分析-Cu" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="cuValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Mn" prop="mnValue">
                <el-input-number v-model="form.mnValue" placeholder="请输入化学成分分析-Mn" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="mnValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Mg" prop="mgValue">
                <el-input-number v-model="form.mgValue" placeholder="请输入化学成分分析-Mg" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="mgValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Zn" prop="znValue">
                <el-input-number v-model="form.znValue" placeholder="请输入化学成分分析-Zn" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="znValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Ni" prop="niValue">
                <el-input-number v-model="form.niValue" placeholder="请输入化学成分分析-Ni" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="niValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Ti" prop="tiValue">
                <el-input-number v-model="form.tiValue" placeholder="请输入化学成分分析-Ti" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="tiValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Cr" prop="crValue">
                <el-input-number v-model="form.crValue" placeholder="请输入化学成分分析-Cr" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="crValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="化学成分分析-Mo" prop="moValue">
                <el-input-number v-model="form.moValue" placeholder="请输入化学成分分析-Mo" :precision="4"/>
                <standard-result-type-tag :standardList="standardList" name="moValue"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出厂检测日期" prop="leaveInspectDate">
                <el-date-picker clearable
                                v-model="form.leaveInspectDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择出厂检测日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入厂检测日期" prop="arriveInspectDate">
                <el-date-picker clearable
                                v-model="form.arriveInspectDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择入厂检测日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机械性能-抗拉强度" prop="tensileStrength">
                <el-input style="width: 80%;" v-model="form.tensileStrength" placeholder="请输入机械性能-抗拉强度"/>
                <standard-result-type-tag :standardList="standardList"
                                          name="tensileStrength"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="屈服强度" prop="succumbStrength">
                <el-input style="width: 80%;" v-model="form.succumbStrength" placeholder="请输入屈服强度"/>
                <standard-result-type-tag :standardList="standardList"
                                          name="succumbStrength"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机械性能-断后伸长率" prop="extend">
                <el-input style="width: 80%;" v-model="form.extend" placeholder="请输入机械性能-断后伸长率"/>
                <standard-result-type-tag :standardList="standardList" name="extend"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机械性能-硬度" prop="hardness">
                <el-input style="width: 80%;" v-model="form.hardness" placeholder="请输入机械性能-硬度"/>
                <standard-result-type-tag :standardList="standardList" name="hardness"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="外观、表面质量" prop="surfaceQuality">
                <el-input style="width: 80%;" v-model="form.surfaceQuality" placeholder="请输入外观、表面质量"/>
                <standard-result-type-tag :standardList="standardList" name="surfaceQuality"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="尺寸" prop="size">
                <el-input style="width: 80%;" v-model="form.size" placeholder="请输入尺寸"/>
                <standard-result-type-tag :standardList="standardList" name="size"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格" prop="specs">
                <el-input style="width: 80%;" v-model="form.specs" placeholder="请输入规格"/>
                <standard-result-type-tag :standardList="standardList" name="specs"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="拉伸强度" prop="pullStrength">
                <el-input style="width: 80%;" v-model="form.pullStrength" placeholder="请输入拉伸强度"/>
                <standard-result-type-tag :standardList="standardList" name="pullStrength"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="延伸率" prop="extendRate">
                <el-input style="width: 80%;" v-model="form.extendRate" placeholder="请输入延伸率"/>
                <standard-result-type-tag :standardList="standardList" name="extendRate"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="力学性能-单丝强度" prop="singleStrength">
                <el-input style="width: 80%;" v-model="form.singleStrength" placeholder="请输入力学性能-单丝强度"/>
                <standard-result-type-tag :standardList="standardList" name="singleStrength"></standard-result-type-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否合格" prop="testPass">
                <el-radio-group v-model="form.testPass">
                  <el-radio
                    v-for="dict in dict.type.yes_no"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12">-->
            <!--              <el-form-item label="质量证书" prop="qualityCertificate">-->
            <!--                <file-upload v-model="form.qualityCertificate"/>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="生产厂检测报告" prop="singleStrength">
                <file-upload v-model="form.productReport"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来料检测报告" prop="singleStrength">
                <file-upload v-model="form.materialReport"/>
              </el-form-item>
            </el-col>

          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="autoGetStatus==='true'" type="success" @click="autoGetInfo">自 动 获 取</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {accAdd, addAction, getAction, getById, updateAction} from '@/api/manage';
import moment from 'moment';
import StandardResultTypeTag from "@/views/develop/factory/factoryTestStandard/StandardResultTypeTag.vue";
import {getConfigKey} from "@/api/system/config";

export default {
  name: "FactoryMaterialMainForm",
  dicts: ["yes_no"],
  components: {StandardResultTypeTag},
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 自动获取配置
      autoGetStatus: 'false',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      url: {
        getById: '/factoryMaterialMain/factoryMaterialMain/',
        add: '/factoryMaterialMain/factoryMaterialMain/add',
        edit: '/factoryMaterialMain/factoryMaterialMain/edit',
      },
      standardList: []
    };
  },
  created() {
    this.getAutoGetStatus();
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        orderId: null,
        goodsId: null,
        saleId: null,
        name: null,
        inspectNumber: null,
        type: null,
        producer: null,
        code: null,
        heatBatchNumber: null,
        batchNumber: null,
        cValue: null,
        pValue: null,
        sValue: null,
        alValue: null,
        siValue: null,
        feValue: null,
        cuValue: null,
        mnValue: null,
        mgValue: null,
        znValue: null,
        niValue: null,
        tiValue: null,
        crValue: null,
        moValue: null,
        leaveInspectDate: null,
        arriveInspectDate: null,
        qualityCertificate: null,
        tensileStrength: null,
        succumbStrength: null,
        extend: null,
        hardness: null,
        surfaceQuality: null,
        size: null,
        specs: null,
        pullStrength: null,
        extendRate: null,
        singleStrength: null,
        productReport: null,
        materialReport: null,
        testPass: '1',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },

    getAutoGetStatus() {
      getConfigKey("autoGet").then(res => {
        if (res) {
          this.autoGetStatus = res.msg;
        } else {
          this.$message.warning("未开启自动获取功能");
        }
      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加原材料（主材）";
    },
    /** 新增按钮操作 */
    handleAddByWorkOrderId(workOrderId, goodsId, goodsSaleId, materialId) {
      this.reset();
      this.form.workOrderId = workOrderId;
      this.form.goodsId = goodsId;
      this.form.goodsSaleId = goodsSaleId;
      this.form.materialId = materialId;
      this.form.batchNumber = "BT" + moment().format("YYYYMMDDHHmmss");
      this.open = true;
      this.getStandardList();
      this.title = "添加原材料（主材）";
    },

    /** 新增按钮操作 */
    handleAddByDaohuoDetailId(daohuoDetailId, goodsId, goodsSaleId, materialId) {
      this.reset();
      this.form.daohuoDetailId = daohuoDetailId;
      this.form.goodsId = goodsId;
      this.form.goodsSaleId = goodsSaleId;
      this.form.materialId = materialId;
      this.getStandardList();
      this.open = true;
      this.title = "添加原材料（主材）";
    },

    handleAddByProduceDetailId(produceRecordDetailId, goodsId, goodsSaleId, materialId) {
      this.reset();
      this.form.produceRecordDetailId = produceRecordDetailId;
      this.form.goodsId = goodsId;
      this.form.goodsSaleId = goodsSaleId;
      this.form.materialId = materialId;
      this.getStandardList();
      this.open = true;
      this.title = "添加原材料（主材）";
    },


    /** 新增按钮操作 */
    handleAddByRukuId(rukuId, goodsId, goodsSaleId, materialId) {
      this.reset();
      this.form.rukuId = rukuId;
      this.form.goodsId = goodsId;
      this.form.goodsSaleId = goodsSaleId;
      this.form.materialId = materialId;
      this.getStandardList();
      this.open = true;
      this.title = "添加原材料（主材）";
    },

    /** 新增按钮操作 */
    handleAddBySampleId(sampleId, goodsId, goodsSaleId, materialId) {
      this.reset();
      this.form.sampleId = sampleId;
      this.form.goodsId = goodsId;
      this.form.goodsSaleId = goodsSaleId;
      this.form.materialId = materialId;
      this.getStandardList();
      this.open = true;
      this.title = "添加原材料（主材）";
    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getById(this.url.getById, id).then(response => {
        this.form = response.data;
        this.form.materialId = response.data.params.goodsMaterialMain;
        this.open = true;
        this.title = "修改原材料（主材）";
        this.getStandardList();
      });
    },
    /** 提交按钮 */
    submitForm() {

      // 各个元素含量的之后不能超过100%
      let totalValue = accAdd(accAdd(accAdd(accAdd(accAdd(accAdd(accAdd(accAdd(accAdd(accAdd(accAdd(accAdd(accAdd(this.form.cValue, this.form.pValue), this.form.sValue), this.form.alValue), this.form.siValue), this.form.feValue), this.form.cuValue), this.form.mnValue), this.form.mgValue), this.form.znValue), this.form.niValue), this.form.tiValue), this.form.crValue), this.form.moValue);
      //判断totalValue 是否为100
      if (totalValue != 100) {
        this.$modal.msgError("各元素含量之和为" + totalValue + ",不等于100%");
        return;
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAction(this.url.edit, this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit('ok');
            });
          } else {
            addAction(this.url.add, this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit('ok');
            });
          }
        }
      });
    },

    getStandardList() {
      let name = "factory_material_main";
      let materialId = this.form.materialId;
      getAction('/factoryTestStandard/factoryTestStandard/getTableColumnsByMaterialId/' + name + "/" + materialId, {}).then(response => {
        this.loading = false;
        this.standardList = response.data;
      });
    },


    autoGetInfo() {
      let that = this;
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        loading.close();
        that.$modal.msgSuccess("数据获取成功");
        for (const standard in that.standardList) {

          if (that.standardList[standard].resultType === '1' || that.standardList[standard].resultType === '2' || that.standardList[standard].resultType === '3' || that.standardList[standard].resultType === '4') {
            that.form[that.standardList[standard].propName] = that.getRandomArbitrary(that.standardList[standard].propValueMin, that.standardList[standard].propValueMax);
          }
          if (that.standardList[standard].resultType === '5' || that.standardList[standard].resultType === '6') {
            that.form[that.standardList[standard].propName] = that.getRandomGt(that.standardList[standard].propValueMin);
          }
          if (that.standardList[standard].resultType === '7' || that.standardList[standard].resultType === '8') {
            that.form[that.standardList[standard].propName] = that.getRandomLt(that.standardList[standard].propValueMax);
          }
        }
      }, 2000);
    },

    getRandomArbitrary(min, max) {
      let that = this;
      let numOne = Number(min);
      let numTow = Number(max);
      if (numTow === 0) {
        return numOne
      }

      if (typeof numOne != 'number' || numOne == NaN) {
        console.log('????请输入数值')
        return
      } else if (typeof numTow != 'number' || numTow == NaN) {
        console.log('请输入数值')
        return
      } else {
        let mathNumber;//随机数
        if (numOne >= numTow) {
          console.log('上面')
          let afterNum = that.dealNum(numOne - numTow);//处理后的数据
          console.log('处理后的', afterNum)
          let resl = Math.random() * afterNum + numTow;
          mathNumber = that.dealNum(resl)
        } else {
          console.log('下面')
          let afterNum = that.dealNum(numTow - numOne);//处理后的数据
          console.log('处理后的', afterNum)
          let resl = Math.random() * afterNum + numOne;
          mathNumber = that.dealNum(resl)
        }
        console.log('最后得到的随机数', mathNumber)
        return mathNumber;
      }
    },

    getRandomGt(min) {
      let num = Number(min);
      let between = this.dealNum(10);//处理后的数据
      let resl = Math.random() * between + num;
      let mathNumber;//随机数
      mathNumber = this.dealNum(resl)
      return mathNumber;
    },

    getRandomLt(max) {
      let num = Number(max);
      let between = this.dealNum(10);//处理后的数据
      let resl = num - Math.random() * between;
      let mathNumber;//随机数
      mathNumber = this.dealNum(resl)
      return mathNumber;
    },

    dealNum(e) {
      if (typeof e != 'number') return;
      let des = e.toString().split('.');
      console.log('处理一', des, e)
      //大于二位小数点
      if (des.length > 1 && des[1].length > 4) {
        return e.toFixed(4)
      } else {
        //没有或小于三位小数点
        return e
      }
    }


  }
};
</script>
